import {queryTargetAllot,queryCtfTargetAllot,getTargetTeamList,queryAllotTopoTargetList,queryAllotTopoTargetList_old,getTargetTeamList_new,queryCtfTarget} from '@/api/drill_compete'
import { getuserinstance } from '@/api/access_new'
import { getDictInfoByName } from '@/api/dict.js'
import { getSceneEditor } from '@/api/process/task'
import { getTaskList } from '@/api/drill'
import { mapGetters } from 'vuex'
//一些公共方法(获取比赛人员和靶标等)，用来判断是否可以计算积分，开始比赛等等
const webscoket = {
    data() {
        return {
            hasUser:false,
            hasTarget:false,
            hasTask:{},//是否有任务
            hasScript: true, // 运维赛需要额外判断是不是所有的运维题都配置了脚本，默认已配置
            optionConfig:{},
            sceneType: '',
            questionSystemShowTab: false, // 答题系统通道配置任务
            hasReportTarget:false,
            config:{}
        }
    },
    computed: {
        ...mapGetters(['showAsset']),
        disStartCompete(){
            if(this.sceneType === 0){
                return !this.hasUser || !this.hasTarget || (this.hlConfig !=2 && !this.hasTask['loop_submit_flag'])
            }
            return !(this.hasUser && this.hasTarget && this.hasScript)
        },
        endClearConfig() {
            return [0,1].includes(this.extension.endClearConfig) ? this.extension.endClearConfig : this.needTip ?  1 : 0;
        },
        disChangeEndClearConfig(){
            return [0,10,13].includes(this.projectInfo.status) || (this.destoryTime < this.serveTime && this.endClearConfig === 1) || this.drillDetail.creator != this.USER_ID
        },
        changeEndClearConfigTip(){
            return this.endClearConfig === 0 && this.drillDetail.progress == 4 && this.destoryTime < this.serveTime ? `${[1, 2, 3, 8, 9].includes(this.drillDetail.type) ? '竞赛' : '演练'}已经结束超过24小时，切换后环境将立即销毁，确认切换？` : '确认切换？'
        },
        endClearConfigShow(){
            return this.endClearConfig ? '是' : '否'
        }
    },
    created(){
        
    },
    mounted(){
    },
    methods: {
        async canStartCompete(type){
            this.sceneType = type;
            await this.getAllProjectGroupMember();
            await this.getTargetTeamList(type);
            if (type === 9) {
                await this.getSettingScript()
                return this.hasUser && this.hasTarget && this.hasScript
            }
            if(type === 0 && this.hlConfig !=2){
                await this.getTaskList('loop_submit_flag')
                return this.hasUser && this.hasTarget && this.hasTask['loop_submit_flag']
            }
            return this.hasUser && this.hasTarget
        },
        getSettingScript() {
            return new Promise(resolve => {
                getTargetTeamList_new({
                    pageIndex: 1,
                    pageSize: 2147483646,
                    sceneId: this.$route.query.id,
                    isFixedFileFlag: 2
                }).then(({ code, data = {} }) => {
                    if (code !== 1) {
                        this.hasScript = false
                        resolve(0)
                    } else {
                        let items = data.items || []
                        this.hasScript = items.every(item => item.scriptId) // 所有的checker题，scriptId字段都不为空
                        resolve(data.total)
                    }
                }).catch(error => {
                    this.hasScript = false
                    resolve(0);
                })
            })
        },
        // 查询场景下是否有人员加入，数据中心包含了人员的接入机器信息
        getAllProjectGroupMember(){
            return new Promise((resolve,reject) => {
                let params = {
                    testId:this.$route.query.id,
                    pageIndex:1,
                    pageSize:1
                }
                getuserinstance(params).then(data => {
                    if(data.code == 1){
                        this.hasUser = data.data.total > 0 // 有数据时，代表人员已添加
                        resolve(data.data.total);
                    }else{
                        this.hasUser = false
                        resolve(0);
                    }
                }).catch(error => {
                    this.hasUser = false
                    resolve(0);
                })
            })
        },
        // 重新判断是否已有用户加入场景
        setHasUser(){
            this.getAllProjectGroupMember();
        },
        // 重新判断是否已有添加题目或任务
        setHasTarget(status){
            this.hasTarget = status;
        },
        setHasTask(status,taskType){
            this.$set(this.hasTask,taskType,status);
        },
        // 查询是否已分配了靶标
        getTargetTeamList(type){
            return new Promise((resolve,reject) => {
                if([1, 4, 7, 8, 9].includes(type)){ // 攻防赛、渗透演练、综合演练
                    let params = {
                        pageIndex:1,
                        pageSize:1,
                        sceneId:this.$route.query.id,
                    }
                    queryTargetAllot(params).then(data => {
                        if(data.code==1){
                            this.hasTarget = data.data.total > 0
                            resolve(data.data.total);
                        }else{
                            this.hasTarget = false;
                            resolve(0);
                        }
                    }).catch(error => {
                        this.hasTarget = false;
                        resolve(0);
                    })
                }else if(type === 0){ // 对抗演练
                    let params = {
                        pageIndex:1,
                        pageSize:1,
                        sceneId:this.$route.query.id,
                        projectId:this.$route.query.prjid
                    }
                    getTargetTeamList(params).then(data => {
                        if(data.code==1){
                            this.hasTarget = data.data.total > 0
                            resolve(data.data.total);
                        }else{
                            this.hasTarget = false;
                            resolve(0);
                        }
                    }).catch(error => {
                        this.hasTarget = false;
                        resolve(0);
                    })
                }else if(type == 2){ // 夺旗赛
                    let params = {
                        pageIndex:1,
                        pageSize:1,
                        sceneId:this.$route.query.id,
                    }
                    queryCtfTargetAllot(params).then(data => {
                        if(data.code==1){
                            this.hasTarget = data.data.total > 0
                            resolve(data.data.total);
                        }else{
                            this.hasTarget = false;
                            resolve(0);
                        }
                    }).catch(error => {
                        this.hasTarget = false;
                        resolve(0);
                    })
                }else if(type == 5){ // 护网演练
                    let params = {
                        pageIndex:1,
                        pageSize:1,
                        projectId:this.$route.query.prjid,
                        sceneId:this.$route.query.id
                    };
                    let queryApi = this.hwType === 0 ? queryAllotTopoTargetList_old : queryAllotTopoTargetList;
                    queryAllotTopoTargetList_old(params).then(data => {
                        if(data.code == 1){
                            if(data.code==1){
                                this.hasTarget = data.data.total > 0
                                resolve(data.data.total);
                            }else{
                                this.hasTarget = false;
                                resolve(0);
                            }
                        }else{
                            this.hasTarget = false;
                            resolve(0);
                        }
                    }).catch(error => {
                        this.hasTarget = false;
                        resolve(0);
                    })
                }else if(type === 10){
                    getSceneEditor(this.$route.query.id).then((data)=>{
                        if(data.code==1){
                            let nodesData = data.data.nodes;
                            let lines = data.data.links;
                            this.processStatus = data.data.status;
                            let finish = nodesData.every(node => {
                                let line = lines.filter(line => line.source === node.id || line.target === node.id)
                                return line.length >= (node.nodeType === "configSing" ? 2 : 1) ? true : false
                            });
                            this.hasTarget = finish ? true : false;
                            resolve(finish ?  1 : 0)
                        }else{
                            this.hasTarget = false;
                            resolve(0);
                        }
                    }).catch(error => {
                        this.hasTarget = false;
                        resolve(0);
                    })
                }
            })
        }, 
        getDictInfoByName () {
            getDictInfoByName({ name: 'displayControl' }).then(res => {
                if (res.code == 1) {
                    if (res.attribute && res.attribute.data.value) {
                        this.optionConfig = JSON.parse(res.attribute.data.value)
                        this.optionConfig.show = true
                    } else {
                        this.optionConfig = { show: false }
                    }
                } else {
                    // 为空时，直接拿show
                    this.optionConfig = { show: false }
                }
            }).catch(error => {
                this.optionConfig = { show: false }
            })
        },
        getTaskList(type){
            return new Promise((resolve,reject) => {
                let params = {
                    "testId":this.$route.query.id,
                    "page":1,
                    "rows":type ? 1 : 999,
                    "taskType":type,
                    "taskMode":'preset',
                }
                getTaskList(params).then(({code,data})=>{
                    if(code==1){
                        if(type){
                            this.$set(this.hasTask,type,data.total > 0);
                        }else{
                            data.items.forEach(({taskType}) => {
                                if(!this.hasTask[taskType]){
                                    this.$set(this.hasTask,taskType,true);
                                }
                            })
                        }
                        resolve()
                    }else{
                        this.hasTask = {};
                        reject()
                    }
                }).catch(error => {
                    this.hasTask = {};
                    reject()
                })
            })
        },
         // 查询是否需要展示额外定制的可视化
        questionSystemShow(name) {
            getDictInfoByName({ name }).then(({ code, attribute, message }) => {
                if (code == 1) {
                    if(name == 'questionSystemConfig'){
                        this.questionSystemShowTab = attribute.data.value == '1' ? true : false;
                    }
                    this.config[name] = attribute.data.value == '1' ? true : false;
                } else {
                    if(name == 'questionSystemConfig'){
                        this.questionSystemShowTab = false;
                    }
                    this.config[name] = false;
                    if (message === '没查询到数据') {
                        // 该数据没有查询到时，并不需要提示错误信息，默认不展示额外的可视化跳转连接
                        return;
                    }
                    this.$Message.error(message);
                }
            });
        },
        getCtfTargetTeamList(){
            let params = {
                pageIndex:1,
                pageSize:1,
                isNeedSubmitFlag: 0,
                submitFlag: 0,
                needEnv: 0,
                isNeedEnv: 0
            }
            queryCtfTarget(this.$route.query.id,params).then(data => {
                if(data.code==1){
                    this.hasReportTarget = data.data.total > 0 ? true  : false;
                }else{
                    this.$Message.error('获取列表失败');
                }
            }).catch(error => {
                this.$Message.error('获取列表失败');
            })
        }
    },
    destroyed(){
        
    }
}

export default webscoket
